$(function () {

    layui.use(['form', 'layer'], function () {
        var form = layui.form(),
            layer = layui.layer;

        var filter_content = $('#layer-open-content').html(),
            fields,
            attachmentData = [];

        // 添加产品明细项
        $('.add-detail-item-btn').click(function () {
            // console.log('add detail item btn clicked.');
            var detail_total = $('.products').children().length;
            var html = `
            <div class="product-detail">
                <h3 class="clearfix">
                    <a href="#detail-item-${detail_total + 1}" id="detail-item-${detail_total + 1}" class="pull-left"># 产品明细（${detail_total + 1}）</a>
                    <button class="btn btn-danger btn-sm pull-right remove-product-item-btn" type="button" style="position: relative; top: -5px;"><i class="icon-trash"></i> 删除该项</button>
                </h3>
                <div class="row">
                    <div class="col-md-4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品</label>
                            <div class="layui-input-block">
                                <input type="hidden" name="details[${detail_total}][manager]">
                                <input type="hidden" name="details[${detail_total}][product_id]">
                                <input type="text" name="details[${detail_total}][pn]" class="layui-input sample_product_select" lay-verify="required" readonly placeholder="产品">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">产品经理</label>
                            <div class="layui-input-block">
                                <input type="text" name="details[${detail_total}][manager_name]" class="layui-input manager-name" lay-verify="required" readonly placeholder="产品经理" style="cursor: not-allowed !important;">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">模块数量</label>
                            <div class="layui-input-block">
                                <input type="text" name="details[${detail_total}][count]" class="layui-input" lay-verify="required" placeholder="模块数量">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">客户名称</label>
                            <div class="layui-input-block">
                                <input type="text" name="details[${detail_total}][customer]" class="layui-input" lay-verify="required" placeholder="客户名称">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">设备品牌</label>
                            <div class="layui-input-block">
                                <select name="details[${detail_total}][brand]" lay-search>
                                    ${vendor_brands}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">设备型号</label>
                            <div class="layui-input-block">
                                <input type="text" name="details[${detail_total}][model]" class="layui-input" placeholder="设备型号">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <div class="layui-form-item" style="margin-bottom: 20px;">
                            <label class="layui-form-label">备注</label>
                            <div class="layui-input-block">
                                <textarea name="details[${detail_total}][note]" class="layui-textarea" rows="6" placeholder="备注"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="layui-form-item">
                            <label class="layui-form-label">要求交期</label>
                            <div class="layui-input-block">
                                <input type="text" name="details[${detail_total}][requirements_date]" class="layui-input is-date" lay-verify="required" readonly placeholder="要求交期">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            `;

            $('.products').append(html);
            // 当添加明细项后避免组件渲染失效，每新增一项明细时则重新进行一遍组件渲染
            form.render();
            // 添加明细项后对时间选择器进行初始化
            insDatetimePicker('.is-date', {
                language: 'zh-CN',
                format: 'yyyy-mm-dd',
                weekStart: 1,
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startDate: new Date(),
                pickerPosition: "bottom-right",
                startView: 2,
                minView: 2,
                forceParse: 0
            });
        });

        // 删除产品明细项
        $('.products').on('click', '.remove-product-item-btn', function () {
            var children_len = $('.products').children().length;
            if (children_len > 1) {
                $(this).parents('.product-detail').remove();
                $('.products .product-detail').each(function (index) {
                    var el = $(this).find('h3:first-child a');
                    el.attr('id', 'detail-item-' + (index + 1));
                    el.attr('href', '#detail-item-' + (index + 1));
                    el.text('# 产品明细（' + (index + 1) + '）');
                });
            } else {
                layer.msg('至少保留一项产品明细', {
                    icon: 0,
                    time: 2000
                });
            }
        });

        // 定义webuploader配置
        var webuploader_option = {
            auto: false,
            server: '/Sample/fileUpload',
            pick: '#filePicker',
            fileVal: 'Filedata',
            accept: {
                title: 'file',
                extensions: 'zip,rar,jpg,png,jpeg,doc,xls,xlsx,docx,pdf'
            },
            method: 'POST',
        };

        // 实例化webuploader
        var uploader = WebUploader.create(webuploader_option);

        // 添加到队列时
        uploader.on('fileQueued', function (file) {
            var fileItem = '<div class="file-item" id="' + file.id + '">' +
                '<div class="pull-left"><i class="file-icon file-icon-ext-' + file.ext + '"></i> ' + file.name + '</div>' +
                '<div class="pull-right"><i class="icon-remove" title="移除该文件"></i></div>' +
                '<div class="clearfix"></div>' +
                '</div>';
            $(webuploader_option.pick).next().append(fileItem);
        });

        // 上传之前
        uploader.on('uploadBeforeSend', function (block, data, headers) {
            var loading = layer.load(2, {
                shade: [0.5, '#fff']    // 0.5 透明度的白色背景
            });
        });

        // 上传错误时
        uploader.on('error', function (code) {
            var msg = '';
            switch (code) {
                case 'Q_EXCEED_NUM_LIMIT':
                    msg = '只能上传一个文件';
                    break;
                case 'Q_EXCEED_SIZE_LIMIT':
                    msg = '文件大小超出限制';
                    break;
                case 'Q_TYPE_DENIED':
                    msg = '文件格式不允许';
                    break;
                case 'F_DUPLICATE':
                    msg = '文件已存在';
                    break;
                default:
                    msg = code;
            }
            layer.msg(msg, {icon: 2, time: 2000});
        });

        //上传成功时
        uploader.on('uploadSuccess', function (file, response) {	//文件了上传成功后触发
            if (response.flag > 0) {
                //当文件上传成功后添加到attachmentData
                var attachmentObject = new Object();
                attachmentObject.savename = response.name;  // 由于后期变动，文件统一重命名，这里将原先的 savename 改为 name
                attachmentObject.ext = response.ext;
                attachmentObject.path = response.path;
                attachmentData.push(attachmentObject);
            } else {
                layer.closeAll();
                layer.msg(response.msg, {icon: 2, time: 2000});
            }
        });

        // 所有文件上传结束时
        uploader.on('uploadFinished', function () {
            // 当文件上传完毕后将数据添加至 formdata 再一并提交
            fields.attachments = attachmentData;
            submitSample().then(function (response) {
                if (response.errno) {
                    layer.closeAll();
                    layer.alert(response.message);
                } else {
                    location.href = '/sample/overview/id/' + response.data.id;
                }
            });
        });

        // 删除队列文件
        $('.uploader-file-queue').on('click', '.icon-remove', function () {
            var id = $(this).parent().parent().attr('id');
            // 删除队列中的文件
            uploader.removeFile(uploader.getFile(id, true));
            // 删除dom节点
            $(this).parent().parent().remove();
        });

        // 初始化页面上的时间选择器
        insDatetimePicker('.is-date', {
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startDate: new Date(),
            pickerPosition: "bottom-right",
            startView: 2,
            minView: 2,
            forceParse: 0
        });

        // 提交样品单数据
        form.on('submit(submitSample)', function (data) {
            fields = data.field;
            // 检查队列是否存在待上传的文件，如果存在则先上传
            if (uploader.getFiles().length) {
                uploader.upload();
            } else {
                var loading = layer.load(2, {
                    shade: [0.5, '#fff']    // 0.5 透明度的白色背景
                });
                submitSample().then(function (response) {
                    if (response.errno) {
                        layer.close(loading);
                        layer.alert(response.message);
                    } else {
                        location.href = '/sample/overview/id/' + response.data.id;
                    }
                });
            }
        });

        function submitSample()
        {
            return new Promise(function (resolve, reject) {
                delete fields.file; // 移除 uploader 携带的 file 属性
                $.post('/sample/store', fields, function (response) {
                    resolve(response);
                }, 'json');
            });
        }

        form.on('submit(productSearch)', function (data) {

            $.ajax({
                url: '/Sample/productSearch',
                type: 'POST',
                data: data.field,
                dataType: 'json',
                success: function (response) {
                    if (response.flag > 0) {
                        var pns = '';
                        for (var key in response.data) {	//拼装所有产品型号数据
                            pns += '<li pro_id="' + response.data[key].id + '" manager="' + response.data[key].manager + '" manager_name="' + response.data[key].nickname + '">' + response.data[key].pn + '</li>\r\n';
                        }
                        $('.product-list-box ul').html(pns);
                    } else {
                        layer.msg(response.msg);
                    }
                }
            });
            return false;
        });

        //点击选择产品展开筛选器
        var pro_element = null;
        $(document).on('click', '.sample_product_select', function (data) {
            pro_element = $(this);
            var filter_dialog = layer.open({
                type: 1,
                title: '选择产品',
                area: ['100%', '100%'],
                shade: ['0.5', '#000'],
                dataType: 'json',
                content: filter_content,
                cancel: function (index, layero) {
                    $('#filter-map input').val('');
                    layer.close(index);
                }
            });
        });

        //重置筛选
        $(document).on('click', '.reset-filter-btn', function () {
            $('#filter-map input').val('');
            layer.closeAll();
            layer.open({
                type: 1,
                title: '选择产品',
                area: ['100%', '100%'],
                shade: ['0.5', '#000'],
                content: filter_content,
                cancel: function (index, layero) {
                    $('#filter-map input').val('');
                    layer.close(index);
                }
            });
        });

        //展开筛选
        $(document).on('click', '.an-more-btn', function () {
            var _this = $(this),
                _flag = _this.attr('flag'),
                _sr_only_items = $(this).parent().prev().find('.overflow');	//获取到当前类别所有隐藏的item
            if (_flag == 'off') {
                _this.removeClass('icon-chevron-down');
                _this.addClass('icon-chevron-up');
                _sr_only_items.css('display', 'inline-block');
                _this.attr('flag', 'on');
            } else {
                _this.removeClass('icon-chevron-up');
                _this.addClass('icon-chevron-down');
                _sr_only_items.css('display', 'none');
                _this.attr('flag', 'off');
            }
        });


        //筛选产品
        $(document).on('click', '.filter-item', function () {
            var _category = $(this).attr('category'),
                _value = $(this).text(),
                _this = $(this);
            if (_category == 'casetemp' || _category == 'wavelength') {
                var _as_name = $(this).attr('as_name');
                $('#filter-map input[name=' + _category + ']').val(_as_name);	//将选中的赋予到筛选表单
            } else {
                $('#filter-map input[name=' + _category + ']').val(_value);	//将选中的赋予到筛选表单
            }
            $.ajax({
                url: '/Sample/productFilter',
                type: 'POST',
                data: {
                    filter: {
                        type: $('#filter-map input[name=type]').val(),
                        wavelength: $('#filter-map input[name=wavelength]').val(),
                        reach: $('#filter-map input[name=reach]').val(),
                        connector: $('#filter-map input[name=connector]').val(),
                        casetemp: $('#filter-map input[name=casetemp]').val()
                    },
                    category: _category
                },
                dataType: 'json',
                success: function (response) {
                    if (response.flag > 0) {
                        var pns = '';
                        for (var key in response.data) {	//拼装所有产品型号数据
                            pns += '<li pro_id="' + response.data[key].id + '" manager="' + response.data[key].manager + '" manager_name="' + response.data[key].nickname + '">' + response.data[key].pn + '</li>\r\n';
                        }
                        for (var k in response.category) {
                            var _selector = '.filter-items-' + k.substring(0, k.length - 1),
                                _category_list = '';
                            for (var i in response.category[k]) {
                                if ((parseInt(i) + 1) > 6) {	//如果记录大于6条则隐藏，反之则显示
                                    if (k == 'types') {
                                        _category_list += '<li category="type" class="filter-item overflow" title="' + response.category[k][i].type + '">' + response.category[k][i].type + '</li>\r\n';
                                    } else if (k == 'wavelengths') {
                                        _category_list += '<li category="wavelength" class="filter-item overflow" as_name="' + response.category[k][i].wavelength + '" title="' + response.category[k][i].wavelength_as_name + '">' + response.category[k][i].wavelength_as_name + '</li>\r\n';
                                    } else if (k == 'reachs') {
                                        _category_list += '<li category="reach" class="filter-item overflow" title="' + response.category[k][i].reach + '">' + response.category[k][i].reach + '</li>\r\n';
                                    } else if (k == 'connectors') {
                                        _category_list += '<li category="connector" class="filter-item overflow" title="' + response.category[k][i].connector + '">' + response.category[k][i].connector + '</li>\r\n';
                                    } else if (k == 'casetemps') {
                                        _category_list += '<li category="casetemp" class="filter-item overflow" as_name="' + response.category[k][i].casetemp + '" title="' + response.category[k][i].casetemp_as_name + '">' + response.category[k][i].casetemp_as_name + '</li>\r\n';
                                    }
                                } else {
                                    if (k == 'types') {
                                        _category_list += '<li category="type" class="filter-item" title="' + response.category[k][i].type + '">' + response.category[k][i].type + '</li>\r\n';
                                    } else if (k == 'wavelengths') {
                                        _category_list += '<li category="wavelength" class="filter-item" as_name="' + response.category[k][i].wavelength + '" title="' + response.category[k][i].wavelength_as_name + '">' + response.category[k][i].wavelength_as_name + '</li>\r\n';
                                    } else if (k == 'reachs') {
                                        _category_list += '<li category="reach" class="filter-item" title="' + response.category[k][i].reach + '">' + response.category[k][i].reach + '</li>\r\n';
                                    } else if (k == 'connectors') {
                                        _category_list += '<li category="connector" class="filter-item" title="' + response.category[k][i].connector + '">' + response.category[k][i].connector + '</li>\r\n';
                                    } else if (k == 'casetemps') {
                                        _category_list += '<li category="casetemp" class="filter-item" as_name="' + response.category[k][i].casetemp + '" title="' + response.category[k][i].casetemp_as_name + '">' + response.category[k][i].casetemp_as_name + '</li>\r\n';
                                    }
                                }
                            }
                            $(_selector).html(_category_list);
                            var children_length = parseInt($(_selector).children('li').length) / 2,	//获取到对应类别的item数量
                                more_btn = $(_selector).parent().next().find('.an-more-btn');
                            //console.log(more_btn);
                            if (children_length <= 6) {	//如果记录大于6条则显示展开按钮，反之则隐藏
                                if (!more_btn.hasClass('sr-only')) {
                                    more_btn.addClass('sr-only');
                                }
                            } else {
                                if (more_btn.hasClass('sr-only')) {
                                    more_btn.removeClass('sr-only');
                                }
                            }
                        }
                        $('.product-list-box ul').html(pns);
                        _this.parent().find('li').removeClass('active');
                        _this.addClass('active');
                    } else {
                        layer.msg(response.msg);
                    }
                }
            });
        });

        //将产品信息添加到栏位
        $(document).on('click', '.product-list-box ul li', function () {
            // 防止添加到栏位时出现空格过多的样式问题，在添加到栏位之前应对数据进行前后空格过滤 $.trim(value);
            pro_element.val($.trim($(this).text()));
            pro_element.prev().val($.trim($(this).attr('pro_id')));
            pro_element.prev().prev().val($.trim($(this).attr('manager')));
            pro_element.parents('.col-md-4').next().find('.manager-name').val($.trim($(this).attr('manager_name')));
            layer.closeAll();
        });


    });

});